package com.zhengdongzulin.zuke.base

import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gyf.immersionbar.ktx.immersionBar
import com.lxj.androidktx.core.toast
import com.lxj.androidktx.core.visible
import com.lxj.androidktx.livedata.StateLiveData
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.zhengdongzulin.zuke.R
import com.zhengdongzulin.zuke.app.data.GlobalInfo
import com.zhengdongzulin.zuke.ext.put
import com.zhengdongzulin.zuke.ext.setClickFinish
import rxhttp.wrapper.param.RxHttp


/**
 * jeff
 * 2021-03-24 10:40:23
 */
abstract class BaseActivity<VM : ViewModel, VB : ViewDataBinding> : AppCompatActivity() {

    lateinit var mShareViewModel: GlobalInfo
    private lateinit var mActivity: AppCompatActivity
    protected lateinit var mViewModel: VM
    protected lateinit var mView: VB

    var isAddActivitys: Boolean = true
    var ifSetStatusBar: Boolean = true
    var isInitDialog: Boolean = false

    protected open fun getAppViewModelProvider(): ViewModelProvider {
        return MyApp().getAppViewModelProvider(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
        mView = DataBindingUtil.setContentView(this, getLayoutResId())

        mShareViewModel = MyApp().getAppViewModelProvider(this).get(GlobalInfo::class.java)
        mViewModel = initVM()
        (mViewModel as BaseViewModel).apply {
            this.mShareViewModel = this@BaseActivity.mShareViewModel
        }
        initView()
        if (ifSetStatusBar)
            setStatusBar()
        if (isAddActivitys || !MyApp.mActivitys.contains(this))
            MyApp.mActivitys.add(this)
        var back = findViewById<View>(R.id.back)
        back?.let {
            it.setClickFinish()
        }
//        if (isInitDialog) {
//            mLoadingDiaog = WidgetUtils.getMiniLoadingDialog(this)
//            mLoadingDiaog = MaterialDialog.Builder(this)
//                .customView(R.layout.zk_dialog_loading_view, false)
//                .build()
//            mLoadingDiaog?.window!!.apply {
//                setGravity(Gravity.CENTER);
//                setLayout(
//                    WindowManager.LayoutParams.WRAP_CONTENT,
//                    WindowManager.LayoutParams.WRAP_CONTENT
//                )
//                var attr = attributes
//                attr.width = UIUtil.dip2px(MyApp().getContext(), 150.0)
//                attributes = attr
//            }
//        }
        initData()
        initListener()
        startObserve()
    }

    fun checkLogin(): Boolean {
        if (mShareViewModel.token.value.isNullOrEmpty()) {
            toast("请您先登录")
            needLogin()
            return false
        }
        return true
    }

    /**
     * color 状态栏颜色
     * isAuto 状态栏字体图标是否自动变色
     * isDrakFont 状态栏是否是黑色，true为黑色，false为白色，默认为true(isAuto为false才起作用)
     * isFit
     */
    open fun setStatusBar(
        color: Int = R.color.transparent,
        isAuto: Boolean = false,
        isDrakFont: Boolean = true,
        isFit: Boolean = false
    ) {
        immersionBar {
            reset()
            statusBarColor(color)
            navigationBarColor(R.color.white)
            navigationBarDarkIcon(true)
            if (isAuto)
                autoStatusBarDarkModeEnable(true)
            statusBarDarkFont(isDrakFont)
            fullScreen(false)
            fitsSystemWindows(isFit)
        }
    }

    abstract fun getLayoutResId(): Int
    abstract fun initVM(): VM
    abstract fun initView()
    abstract fun initData()
    abstract fun initListener()
    abstract fun startObserve()

    fun setTitleContent(title: String) {
        var title_content = findViewById<TextView>(R.id.title_content)
        title_content?.let {
            it.text = title
        }
    }

    fun setRightButton(rightContent: String, click: () -> Unit) {
        var right_butoon = findViewById<TextView>(R.id.right_butoon)
        right_butoon?.let {
            it.text = rightContent
            it.visible()
            it.setOnClickListener { click() }
        }
    }

    private fun isSoftShowing(): Boolean {
        //获取当前屏幕内容的高度
        var screenHeight = window.decorView.getHeight();
        //获取View可见区域的bottom
        var rect = Rect();
        window.decorView.getWindowVisibleDisplayFrame(rect);

        return screenHeight * 2 / 3 > rect.bottom
    }

    fun hideKeyboard() {
        val inputMethodManager =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (isSoftShowing())
            inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
    }


    fun <T> getObserver(liveData: StateLiveData<T>): Observer<StateLiveData.State> = Observer {
        when (liveData.state.value) {
            StateLiveData.State.Error, StateLiveData.State.Empty -> {
                toast(liveData.errMsg)
                if ("NEED_LOGIN".equals(liveData.errMsg)) {
                    mShareViewModel.token.value = ""
                    checkLogin()
                }
            }
        }
    }

    fun <T> getObserver(
        liveData: StateLiveData<T>,
        refreshLayout: SmartRefreshLayout
    ): Observer<StateLiveData.State> {
        refreshLayout.finishRefresh()
        refreshLayout.finishLoadMore()
        return Observer {
            when (liveData.state.value) {
                StateLiveData.State.Error, StateLiveData.State.Empty -> toast(liveData.errMsg)
            }
        }
    }

    fun <T> observer(liveData: StateLiveData<T>) {
        when (liveData.state.value) {
            StateLiveData.State.Error, StateLiveData.State.Empty -> toast(liveData.errMsg)
        }
    }

    val START_LOGIN_REQUEST = 1

    fun getObserver(errStr: String): Observer<StateLiveData.State> = Observer {
        when (it) {
            StateLiveData.State.Error, StateLiveData.State.Empty -> toast(errStr)
        }
    }

    fun needLogin() {
        try {
            val intent = Intent()
            intent.component =
                ComponentName(packageName, "com.customer.service.login.LoginActivity")
            intent.put("fromType", "apartment")
            startActivityForResult(intent, START_LOGIN_REQUEST)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun gotoHouseToNavActivity(lat: String, lng: String, address: String, loudongName: String) {
        try {
            val intent = Intent()
            intent.component =
                ComponentName(packageName, "com.customer.homepage.housetonav.HouseToNavActivity")
            intent.put("lat", lat)
            intent.put("lng", lng)
            intent.put("address", address)
            intent.put("loudongName", loudongName)
            startActivityForResult(intent, START_LOGIN_REQUEST)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == START_LOGIN_REQUEST && resultCode == Activity.RESULT_OK) {
            mShareViewModel.token.value = data?.getStringExtra("token")
            RxHttp.setOnParamAssembly {
                if (!mShareViewModel.token.value.isNullOrEmpty()) {
                    it.addHeader("Authorization", mShareViewModel.token.value)
                }
                it
            }
        }
    }

    override fun onDestroy() {
        if (MyApp.mActivitys.contains(this))
            MyApp.mActivitys.remove(this)

        super.onDestroy()
    }


}